// 商品数据
const products = [
    // 手机数码类
    {
        id: 1,
        name: "iPhone 15 Pro",
        price: 7999,
        originalPrice: 8999,
        description: "超强A17芯片，4800万像素主摄，钛金属边框",
        category: "phone",
        image: "https://images.unsplash.com/photo-1695048133142-1a20484d2569?w=500&auto=format&fit=crop&q=60",
        stock: 100,
        sales: 50
    },
    {
        id: 2,
        name: "华为 Mate 60 Pro",
        price: 6999,
        originalPrice: 7999,
        description: "麒麟9000S芯片，超长续航，卫星通信",
        category: "phone",
        image: "https://images.unsplash.com/photo-1598327105666-5b89351aff97?w=500&auto=format&fit=crop&q=60",
        stock: 60,
        sales: 40
    },
    {
        id: 3,
        name: "小米14 Pro",
        price: 4999,
        originalPrice: 5499,
        description: "骁龙8 Gen 3，徕卡光学，超长续航",
        category: "phone",
        image: "https://images.unsplash.com/photo-1598327105666-5b89351aff97?w=500&auto=format&fit=crop&q=60",
        stock: 100,
        sales: 80
    },
    {
        id: 4,
        name: "Apple Watch Series 9",
        price: 3299,
        originalPrice: 3599,
        description: "全天候视网膜显示屏，心率监测，运动追踪",
        category: "phone",
        image: "https://images.unsplash.com/photo-1579586337278-3befd40fd17a?w=500&auto=format&fit=crop&q=60",
        stock: 80,
        sales: 30
    },
    {
        id: 5,
        name: "AirPods Pro 2",
        price: 1999,
        originalPrice: 2299,
        description: "主动降噪，空间音频，USB-C充电",
        category: "phone",
        image: "https://images.unsplash.com/photo-1600294037681-c80b4cb5b434?w=500&auto=format&fit=crop&q=60",
        stock: 150,
        sales: 100
    },

    // 电脑办公类
    {
        id: 6,
        name: "MacBook Pro M3",
        price: 14999,
        originalPrice: 15999,
        description: "M3芯片，14英寸视网膜显示屏，超长续航",
        category: "computer",
        image: "https://images.unsplash.com/photo-1517336714731-489689fd1ca8?w=500&auto=format&fit=crop&q=60",
        stock: 50,
        sales: 20
    },
    {
        id: 7,
        name: "戴尔 XPS 13",
        price: 9999,
        originalPrice: 10999,
        description: "13代酷睿，4K触控屏，超轻薄设计",
        category: "computer",
        image: "https://images.unsplash.com/photo-1593642632823-8f785ba67e45?w=500&auto=format&fit=crop&q=60",
        stock: 30,
        sales: 15
    },
    {
        id: 8,
        name: "联想 ThinkPad X1",
        price: 12999,
        originalPrice: 13999,
        description: "商务旗舰，军工级品质，超长续航",
        category: "computer",
        image: "https://images.unsplash.com/photo-1593642632823-8f785ba67e45?w=500&auto=format&fit=crop&q=60",
        stock: 40,
        sales: 25
    },
    {
        id: 9,
        name: "罗技 MX Master 3S",
        price: 799,
        originalPrice: 899,
        description: "人体工学设计，精准追踪，多设备切换",
        category: "computer",
        image: "https://images.unsplash.com/photo-1527814050087-3793815479db?w=500&auto=format&fit=crop&q=60",
        stock: 200,
        sales: 150
    },
    {
        id: 10,
        name: "机械键盘",
        price: 499,
        originalPrice: 599,
        description: "青轴机械轴，RGB背光，人体工学设计",
        category: "computer",
        image: "https://images.unsplash.com/photo-1618384887929-16ec33fab9ef?w=500&auto=format&fit=crop&q=60",
        stock: 100,
        sales: 80
    },

    // 服装鞋包类
    {
        id: 11,
        name: "Nike Air Force 1",
        price: 899,
        originalPrice: 999,
        description: "经典白色，舒适透气，百搭款式",
        category: "clothing",
        image: "https://images.unsplash.com/photo-1542291026-7eec264c27ff?w=500&auto=format&fit=crop&q=60",
        stock: 200,
        sales: 150
    },
    {
        id: 12,
        name: "Adidas 运动套装",
        price: 599,
        originalPrice: 699,
        description: "速干面料，舒适透气，时尚设计",
        category: "clothing",
        image: "https://images.unsplash.com/photo-1515886657613-9f3515b0c78f?w=500&auto=format&fit=crop&q=60",
        stock: 150,
        sales: 100
    },
    {
        id: 13,
        name: "LV 手提包",
        price: 15999,
        originalPrice: 17999,
        description: "经典款式，真皮材质，时尚百搭",
        category: "clothing",
        image: "https://images.unsplash.com/photo-1584917865442-de89df76afd3?w=500&auto=format&fit=crop&q=60",
        stock: 20,
        sales: 15
    },
    {
        id: 14,
        name: "优衣库羽绒服",
        price: 699,
        originalPrice: 799,
        description: "轻便保暖，时尚百搭，多色可选",
        category: "clothing",
        image: "https://images.unsplash.com/photo-1539533018447-63fcce2678e3?w=500&auto=format&fit=crop&q=60",
        stock: 100,
        sales: 80
    },
    {
        id: 15,
        name: "ZARA 休闲裤",
        price: 299,
        originalPrice: 399,
        description: "舒适面料，修身版型，百搭款式",
        category: "clothing",
        image: "https://images.unsplash.com/photo-1473966968600-fa801b869a1a?w=500&auto=format&fit=crop&q=60",
        stock: 200,
        sales: 150
    },

    // 食品生鲜类
    {
        id: 16,
        name: "有机蔬菜礼盒",
        price: 199,
        originalPrice: 299,
        description: "新鲜采摘，无农药，营养丰富",
        category: "food",
        image: "https://images.unsplash.com/photo-1542838132-92c53300491e?w=500&auto=format&fit=crop&q=60",
        stock: 50,
        sales: 30
    },
    {
        id: 17,
        name: "进口水果礼盒",
        price: 299,
        originalPrice: 399,
        description: "精选进口水果，新鲜直达",
        category: "food",
        image: "https://images.unsplash.com/photo-1610832958506-aa56368176cf?w=500&auto=format&fit=crop&q=60",
        stock: 40,
        sales: 25
    },
    {
        id: 18,
        name: "有机大米",
        price: 99,
        originalPrice: 129,
        description: "东北黑土地，有机种植，营养丰富",
        category: "food",
        image: "https://images.unsplash.com/photo-1586201375761-83865001e31c?w=500&auto=format&fit=crop&q=60",
        stock: 100,
        sales: 80
    },
    {
        id: 19,
        name: "进口牛肉",
        price: 199,
        originalPrice: 299,
        description: "澳洲进口，优质牛肉，新鲜冷冻",
        category: "food",
        image: "https://images.unsplash.com/photo-1607623814075-e51df1bdc82f?w=500&auto=format&fit=crop&q=60",
        stock: 30,
        sales: 20
    },
    {
        id: 20,
        name: "海鲜礼盒",
        price: 399,
        originalPrice: 499,
        description: "新鲜海鲜，冷链配送，品质保证",
        category: "food",
        image: "https://images.unsplash.com/photo-1519708227418-c8fd9a32b7a2?w=500&auto=format&fit=crop&q=60",
        stock: 25,
        sales: 15
    },

    // 家居家装类
    {
        id: 21,
        name: "北欧风格沙发",
        price: 3999,
        originalPrice: 4999,
        description: "简约现代，舒适耐用，多色可选",
        category: "home",
        image: "https://images.unsplash.com/photo-1555041469-a586c61ea9bc?w=500&auto=format&fit=crop&q=60",
        stock: 20,
        sales: 10
    },
    {
        id: 22,
        name: "智能台灯",
        price: 299,
        originalPrice: 399,
        description: "护眼设计，智能调光，节能环保",
        category: "home",
        image: "https://images.unsplash.com/photo-1507473885765-e6ed057f782c?w=500&auto=format&fit=crop&q=60",
        stock: 100,
        sales: 80
    },
    {
        id: 23,
        name: "记忆棉床垫",
        price: 1999,
        originalPrice: 2499,
        description: "人体工学设计，舒适支撑，改善睡眠",
        category: "home",
        image: "https://images.unsplash.com/photo-1522771739844-6a9f6d5f14af?w=500&auto=format&fit=crop&q=60",
        stock: 30,
        sales: 20
    },
    {
        id: 24,
        name: "智能窗帘",
        price: 599,
        originalPrice: 799,
        description: "智能控制，遮光效果好，静音设计",
        category: "home",
        image: "https://images.unsplash.com/photo-1513694203232-719a280e022f?w=500&auto=format&fit=crop&q=60",
        stock: 50,
        sales: 30
    },
    {
        id: 25,
        name: "实木餐桌",
        price: 2999,
        originalPrice: 3999,
        description: "优质实木，环保漆面，耐用美观",
        category: "home",
        image: "https://images.unsplash.com/photo-1577140917170-285929fb55b7?w=500&auto=format&fit=crop&q=60",
        stock: 15,
        sales: 8
    }
];

// 限时秒杀商品数据
const seckillProducts = [
    {
        id: 101,
        name: "时尚休闲运动鞋",
        price: 199,
        originalPrice: 399,
        description: "轻便透气，减震缓冲，多色可选",
        category: "clothing",
        image: "https://images.unsplash.com/photo-1608231387042-66d1773070a5?w=500&auto=format&fit=crop&q=60",
        stock: 50,
        sold: 30,
        countdown: 7200 // 2小时，以秒为单位
    },
    {
        id: 102,
        name: "智能手表",
        price: 299,
        originalPrice: 599,
        description: "心率监测，运动追踪，防水设计",
        category: "phone",
        image: "https://images.unsplash.com/photo-1523275335684-37898b6baf30?w=500&auto=format&fit=crop&q=60",
        stock: 30,
        sold: 15,
        countdown: 7200
    },
    {
        id: 103,
        name: "无线蓝牙耳机",
        price: 159,
        originalPrice: 299,
        description: "主动降噪，长续航，舒适佩戴",
        category: "phone",
        image: "https://images.unsplash.com/photo-1606220588913-b3aacb4d2f46?w=500&auto=format&fit=crop&q=60",
        stock: 100,
        sold: 60,
        countdown: 7200
    },
    {
        id: 104,
        name: "便携式充电宝",
        price: 89,
        originalPrice: 199,
        description: "20000mAh大容量，快充技术，小巧便携",
        category: "phone",
        image: "https://images.unsplash.com/photo-1607083206968-13611e3d76db?w=500&auto=format&fit=crop&q=60",
        stock: 200,
        sold: 120,
        countdown: 7200
    }
];

// 初始化页面
function initPage() {
    initEventListeners();
    updateLoginUI();
    loadProducts();
    initCart();
    initCountdown();
    initSeckill();
    initTheme();
    initFloatingAd();
    initCustomerService();
    initStickyNav();
}

// 初始化事件监听器
function initEventListeners() {
    // 登录按钮
    const loginBtn = document.getElementById('loginBtn');
    if (loginBtn) {
        loginBtn.addEventListener('click', (e) => {
            e.preventDefault();
            showLoginModal();
        });
    }

    // 注册按钮
    const registerBtn = document.getElementById('registerBtn');
    if (registerBtn) {
        registerBtn.addEventListener('click', (e) => {
            e.preventDefault();
            showRegisterModal();
        });
    }

    // 个人信息按钮点击事件
    const profileLink = document.querySelector('.profile');
    if (profileLink) {
        profileLink.addEventListener('click', (e) => {
            e.preventDefault();
            if (!isLoggedIn()) {
                showMessage('请先登录');
                showLoginModal();
                return;
            }
            showProfileModal();
        });
    }

    // 修改密码按钮点击事件
    const changePasswordBtn = document.getElementById('changePasswordBtn');
    if (changePasswordBtn) {
        changePasswordBtn.addEventListener('click', () => {
            hideProfileModal();
            showChangePasswordModal();
        });
    }

    // 退出登录按钮点击事件
    const logoutBtn = document.getElementById('logoutBtn');
    if (logoutBtn) {
        logoutBtn.addEventListener('click', handleLogout);
    }

    // 修改密码表单提交事件
    const changePasswordForm = document.getElementById('changePasswordForm');
    if (changePasswordForm) {
        changePasswordForm.addEventListener('submit', handleChangePassword);
    }

    // 关闭按钮
    const closeButtons = document.querySelectorAll('.modal .close');
    closeButtons.forEach(button => {
        button.addEventListener('click', () => {
            const modal = button.closest('.modal');
            if (modal) {
                modal.style.display = 'none';
            }
        });
    });

    // 点击模态框外部关闭
    window.addEventListener('click', (e) => {
        if (e.target.classList.contains('modal')) {
            e.target.style.display = 'none';
        }
    });

    // 登录表单提交
    const loginForm = document.getElementById('loginForm');
    if (loginForm) {
        loginForm.addEventListener('submit', handleLogin);
    }

    // 注册表单提交
    const registerForm = document.getElementById('registerForm');
    if (registerForm) {
        registerForm.addEventListener('submit', handleRegister);
    }

    // 搜索按钮点击事件
    const searchBtn = document.getElementById('searchBtn');
    if (searchBtn) {
        searchBtn.addEventListener('click', handleSearch);
    }

    // 搜索框回车事件
    const searchInput = document.getElementById('searchInput');
    if (searchInput) {
        searchInput.addEventListener('keypress', (e) => {
            if (e.key === 'Enter') {
                handleSearch();
            }
        });
    }

    // 分类点击事件
    const categoryItems = document.querySelectorAll('.category-list a');
    categoryItems.forEach(item => {
        item.addEventListener('click', (e) => {
            e.preventDefault();
            const category = e.target.dataset.category;
            filterByCategory(category);
            
            // 更新选中状态
            categoryItems.forEach(i => i.classList.remove('active'));
            e.target.classList.add('active');
        });
    });

    // 订单按钮点击事件
    const ordersBtn = document.querySelector('.orders');
    if (ordersBtn) {
        ordersBtn.addEventListener('click', (e) => {
            e.preventDefault();
            if (!isLoggedIn()) {
                showMessage('请先登录');
                showLoginModal();
                return;
            }
            showOrderModal();
        });
    }

    // 商品详情数量选择器
    const detailQuantityInput = document.getElementById('detailQuantity');
    const minusBtn = document.querySelector('.quantity-selector .minus');
    const plusBtn = document.querySelector('.quantity-selector .plus');
    
    if (minusBtn && plusBtn && detailQuantityInput) {
        minusBtn.addEventListener('click', () => {
            const currentValue = parseInt(detailQuantityInput.value);
            if (currentValue > 1) {
                detailQuantityInput.value = currentValue - 1;
            }
        });

        plusBtn.addEventListener('click', () => {
            const currentValue = parseInt(detailQuantityInput.value);
            detailQuantityInput.value = currentValue + 1;
        });

        detailQuantityInput.addEventListener('change', () => {
            if (parseInt(detailQuantityInput.value) < 1) {
                detailQuantityInput.value = 1;
            }
        });
    }

    // 商品详情加入购物车按钮
    const addToCartDetailBtn = document.getElementById('addToCartDetail');
    if (addToCartDetailBtn) {
        addToCartDetailBtn.addEventListener('click', () => {
            const productId = parseInt(addToCartDetailBtn.dataset.productId);
            const quantity = parseInt(document.getElementById('detailQuantity').value);
            addToCartWithQuantity(productId, quantity);
        });
    }

    // 图片预览功能
    const imagePreviewModal = document.getElementById('imagePreviewModal');
    const previewImage = document.getElementById('previewImage');
    let isZoomed = false;

    if (imagePreviewModal && previewImage) {
        // 点击图片预览模态框关闭
        imagePreviewModal.addEventListener('click', () => {
            imagePreviewModal.style.display = 'none';
            previewImage.classList.remove('zoomed');
            isZoomed = false;
        });

        // 点击图片切换缩放状态
        previewImage.addEventListener('click', (e) => {
            e.stopPropagation();
            isZoomed = !isZoomed;
            previewImage.classList.toggle('zoomed', isZoomed);
        });
    }

    // 轮播图功能
    initCarousel();
}

// 添加轮播图初始化函数
function initCarousel() {
    const carousel = document.querySelector('.carousel');
    const items = carousel.querySelectorAll('.carousel-item');
    const indicators = carousel.querySelectorAll('.indicator');
    const prevBtn = carousel.querySelector('.prev');
    const nextBtn = carousel.querySelector('.next');
    let currentIndex = 0;
    let interval;

    // 自动播放
    function startAutoPlay() {
        interval = setInterval(() => {
            nextSlide();
        }, 5000);
    }

    // 停止自动播放
    function stopAutoPlay() {
        clearInterval(interval);
    }

    // 切换到指定幻灯片
    function goToSlide(index) {
        items[currentIndex].classList.remove('active');
        indicators[currentIndex].classList.remove('active');
        currentIndex = (index + items.length) % items.length;
        items[currentIndex].classList.add('active');
        indicators[currentIndex].classList.add('active');
    }

    // 下一张幻灯片
    function nextSlide() {
        goToSlide(currentIndex + 1);
    }

    // 上一张幻灯片
    function prevSlide() {
        goToSlide(currentIndex - 1);
    }

    // 添加事件监听
    if (prevBtn && nextBtn) {
        prevBtn.addEventListener('click', () => {
            stopAutoPlay();
            prevSlide();
            startAutoPlay();
        });

        nextBtn.addEventListener('click', () => {
            stopAutoPlay();
            nextSlide();
            startAutoPlay();
        });
    }

    // 指示器点击事件
    indicators.forEach((indicator, index) => {
        indicator.addEventListener('click', () => {
            stopAutoPlay();
            goToSlide(index);
            startAutoPlay();
        });
    });

    // 鼠标悬停时暂停自动播放
    carousel.addEventListener('mouseenter', stopAutoPlay);
    carousel.addEventListener('mouseleave', startAutoPlay);

    // 开始自动播放
    startAutoPlay();
}

// 更新登录状态UI
function updateLoginUI() {
    const loginBtn = document.getElementById('loginBtn');
    const registerBtn = document.getElementById('registerBtn');
    const profileLink = document.querySelector('.profile');

    if (isLoggedIn()) {
        const username = localStorage.getItem('username');
        if (loginBtn) loginBtn.style.display = 'none';
        if (registerBtn) registerBtn.style.display = 'none';
        if (profileLink) {
            profileLink.textContent = username;
            profileLink.style.display = 'inline';
        }
    } else {
        if (loginBtn) loginBtn.style.display = 'inline';
        if (registerBtn) registerBtn.style.display = 'inline';
        if (profileLink) profileLink.style.display = 'none';
    }
}

// 处理登录
function handleLogin(event) {
    event.preventDefault();
    const username = document.getElementById('loginUsername').value;
    const password = document.getElementById('loginPassword').value;

    if (username && password) {
        localStorage.setItem('isLoggedIn', 'true');
        localStorage.setItem('username', username);
        showMessage('登录成功');
        hideLoginModal();
        updateLoginUI();
    } else {
        showMessage('请输入用户名和密码');
    }
}

// 处理注册
function handleRegister(event) {
    event.preventDefault();
    const username = document.getElementById('registerUsername').value;
    const password = document.getElementById('registerPassword').value;
    const confirmPassword = document.getElementById('confirmPassword').value;

    if (!username || !password || !confirmPassword) {
        showMessage('请填写所有字段');
        return;
    }

    if (password !== confirmPassword) {
        showMessage('两次输入的密码不一致');
        return;
    }

    localStorage.setItem('isLoggedIn', 'true');
    localStorage.setItem('username', username);
    showMessage('注册成功');
    hideRegisterModal();
    updateLoginUI();
}

// 显示登录模态框
function showLoginModal() {
    const loginModal = document.getElementById('loginModal');
    if (loginModal) {
        loginModal.style.display = 'block';
    }
}

// 隐藏登录模态框
function hideLoginModal() {
    const loginModal = document.getElementById('loginModal');
    if (loginModal) {
        loginModal.style.display = 'none';
    }
}

// 显示注册模态框
function showRegisterModal() {
    const registerModal = document.getElementById('registerModal');
    if (registerModal) {
        registerModal.style.display = 'block';
    }
}

// 隐藏注册模态框
function hideRegisterModal() {
    const registerModal = document.getElementById('registerModal');
    if (registerModal) {
        registerModal.style.display = 'none';
    }
}

// 显示消息提示
function showMessage(message) {
    const messageBox = document.createElement('div');
    messageBox.className = 'message-box';
    messageBox.textContent = message;
    document.body.appendChild(messageBox);

    setTimeout(() => {
        messageBox.remove();
    }, 2000);
}

// 检查登录状态
function isLoggedIn() {
    return localStorage.getItem('isLoggedIn') === 'true';
}

// 加载商品列表
function loadProducts(filteredProducts = products) {
    const productList = document.querySelector('.product-list');
    if (!productList) return;

    productList.innerHTML = filteredProducts.map(product => `
        <div class="product-card" onclick="showProductDetail(${product.id})">
            <img src="${product.image}" alt="${product.name}" class="product-image" onclick="event.stopPropagation(); showImagePreview('${product.image}', '${product.name}')">
            <div class="product-info">
                <h3 class="product-name">${product.name}</h3>
                <p class="product-description">${product.description}</p>
                <div class="product-price">¥${product.price}</div>
                <button class="add-to-cart-btn" onclick="event.stopPropagation(); addToCart(${product.id})">加入购物车</button>
            </div>
        </div>
    `).join('');
}

// 处理搜索
function handleSearch() {
    const searchInput = document.getElementById('searchInput');
    const keyword = searchInput.value.trim().toLowerCase();
    
    if (keyword) {
        const filteredProducts = products.filter(product => 
            product.name.toLowerCase().includes(keyword) || 
            product.description.toLowerCase().includes(keyword)
        );
        loadProducts(filteredProducts);
    } else {
        loadProducts();
    }
}

// 按分类筛选商品
function filterByCategory(category) {
    if (category === 'all') {
        loadProducts();
    } else {
        const filteredProducts = products.filter(product => product.category === category);
        loadProducts(filteredProducts);
    }
}

// 添加到购物车
function addToCart(productId) {
    if (!isLoggedIn()) {
        showMessage('请先登录');
        showLoginModal();
        return;
    }

    // 获取购物车数据
    let cart = JSON.parse(localStorage.getItem('cart') || '[]');
    
    // 查找商品是否已在购物车中
    const existingItem = cart.find(item => item.id === productId);
    
    if (existingItem) {
        existingItem.quantity += 1;
    } else {
        // 获取商品信息
        const product = products.find(p => p.id === productId);
        if (product) {
            cart.push({
                ...product,
                quantity: 1,
                selected: true
            });
        }
    }
    
    // 保存购物车数据
    localStorage.setItem('cart', JSON.stringify(cart));
    
    // 更新待付款订单中的商品数量
    updateOrderProductQuantity(productId, existingItem ? existingItem.quantity : 1);
    
    showMessage('已添加到购物车');
}

// 初始化购物车
function initCart() {
    const cartBtn = document.querySelector('.cart');
    const cartSidebar = document.getElementById('cartSidebar');
    const cartOverlay = document.getElementById('cartOverlay');
    const closeCartBtn = document.querySelector('.close-cart');
    const checkoutBtn = document.querySelector('.checkout-btn');

    // 打开购物车
    if (cartBtn) {
        cartBtn.addEventListener('click', (e) => {
            e.preventDefault();
            if (!isLoggedIn()) {
                showMessage('请先登录');
                showLoginModal();
                return;
            }
            cartSidebar.classList.add('active');
            cartOverlay.classList.add('active');
            updateCart();
        });
    }

    // 关闭购物车
    if (closeCartBtn) {
        closeCartBtn.addEventListener('click', () => {
            cartSidebar.classList.remove('active');
            cartOverlay.classList.remove('active');
        });
    }

    // 点击遮罩层关闭购物车
    if (cartOverlay) {
        cartOverlay.addEventListener('click', () => {
            cartSidebar.classList.remove('active');
            cartOverlay.classList.remove('active');
        });
    }

    // 结算按钮
    if (checkoutBtn) {
        checkoutBtn.addEventListener('click', handleCheckout);
    }
}

// 更新购物车
function updateCart() {
    const cartItems = document.querySelector('.cart-items');
    const totalPriceElement = document.querySelector('.total-price');
    if (!cartItems || !totalPriceElement) return;

    const cart = JSON.parse(localStorage.getItem('cart') || '[]');
    
    if (cart.length === 0) {
        cartItems.innerHTML = '<div class="empty-cart">购物车是空的</div>';
        totalPriceElement.textContent = '¥0.00';
        return;
    }

    let total = 0;
    cartItems.innerHTML = cart.map(item => {
        const subtotal = item.price * item.quantity;
        total += subtotal;
        return `
            <div class="cart-item" data-id="${item.id}">
                <img src="${item.image}" alt="${item.name}" class="cart-item-image">
                <div class="cart-item-info">
                    <div class="cart-item-name">${item.name}</div>
                    <div class="cart-item-price">¥${item.price}</div>
                    <div class="cart-item-quantity">
                        <button class="quantity-btn minus">-</button>
                        <input type="number" class="quantity-input" value="${item.quantity}" min="1">
                        <button class="quantity-btn plus">+</button>
                        <span class="remove-item">删除</span>
                    </div>
                </div>
            </div>
        `;
    }).join('');

    totalPriceElement.textContent = `¥${total.toFixed(2)}`;

    // 添加数量调整和删除事件
    addCartItemEvents();
}

// 添加购物车商品事件
function addCartItemEvents() {
    const cartItems = document.querySelector('.cart-items');
    if (!cartItems) return;

    // 数量减少按钮
    cartItems.querySelectorAll('.minus').forEach(btn => {
        btn.addEventListener('click', (e) => {
            const item = e.target.closest('.cart-item');
            const id = parseInt(item.dataset.id);
            updateCartItemQuantity(id, -1);
        });
    });

    // 数量增加按钮
    cartItems.querySelectorAll('.plus').forEach(btn => {
        btn.addEventListener('click', (e) => {
            const item = e.target.closest('.cart-item');
            const id = parseInt(item.dataset.id);
            updateCartItemQuantity(id, 1);
        });
    });

    // 数量输入框
    cartItems.querySelectorAll('.quantity-input').forEach(input => {
        input.addEventListener('change', (e) => {
            const item = e.target.closest('.cart-item');
            const id = parseInt(item.dataset.id);
            const newQuantity = parseInt(e.target.value);
            if (newQuantity > 0) {
                updateCartItemQuantity(id, 0, newQuantity);
            }
        });
    });

    // 删除按钮
    cartItems.querySelectorAll('.remove-item').forEach(btn => {
        btn.addEventListener('click', (e) => {
            const item = e.target.closest('.cart-item');
            const id = parseInt(item.dataset.id);
            removeCartItem(id);
        });
    });
}

// 更新购物车商品数量
function updateCartItemQuantity(id, change, newQuantity = null) {
    let cart = JSON.parse(localStorage.getItem('cart') || '[]');
    const itemIndex = cart.findIndex(item => item.id === id);
    
    if (itemIndex > -1) {
        if (newQuantity !== null) {
            cart[itemIndex].quantity = newQuantity;
        } else {
            cart[itemIndex].quantity += change;
        }

        if (cart[itemIndex].quantity < 1) {
            cart.splice(itemIndex, 1);
        }
        
        localStorage.setItem('cart', JSON.stringify(cart));
        updateCart();
        updateOrderProductQuantity(id, cart[itemIndex]?.quantity || 0);
    }
}

// 更新订单中商品数量
function updateOrderProductQuantity(productId, quantity) {
    let orders = JSON.parse(localStorage.getItem('orders') || '[]');
    let updated = false;

    orders = orders.map(order => {
        if (order.status === 'PENDING') {
            const productIndex = order.products.findIndex(p => p.id === productId);
            if (productIndex > -1) {
                order.products[productIndex].quantity = quantity;
                // 更新订单总金额
                order.total = order.products.reduce((sum, item) => sum + item.price * item.quantity, 0);
                updated = true;
            }
        }
        return order;
    });

    if (updated) {
        localStorage.setItem('orders', JSON.stringify(orders));
        loadOrders();
    }
}

// 删除购物车商品
function removeCartItem(id) {
    let cart = JSON.parse(localStorage.getItem('cart') || '[]');
    cart = cart.filter(item => item.id !== id);
    localStorage.setItem('cart', JSON.stringify(cart));
    updateCart();
    removeOrderProduct(id);
    showMessage('商品已删除');
}

// 从订单中删除商品
function removeOrderProduct(productId) {
    let orders = JSON.parse(localStorage.getItem('orders') || '[]');
    let updated = false;

    orders = orders.map(order => {
        if (order.status === 'PENDING') {
            const originalLength = order.products.length;
            order.products = order.products.filter(p => p.id !== productId);
            
            if (order.products.length !== originalLength) {
                // 更新订单总金额
                order.total = order.products.reduce((sum, item) => sum + item.price * item.quantity, 0);
                updated = true;
            }
        }
        return order;
    });

    if (updated) {
        localStorage.setItem('orders', JSON.stringify(orders));
        loadOrders();
    }
}

// 显示订单模态框
function showOrderModal() {
    const orderModal = document.getElementById('orderModal');
    if (orderModal) {
        orderModal.style.display = 'block';
        loadOrders();
    }
}

// 隐藏订单模态框
function hideOrderModal() {
    const orderModal = document.getElementById('orderModal');
    if (orderModal) {
        orderModal.style.display = 'none';
    }
}

// 加载订单列表
function loadOrders() {
    const orderList = document.querySelector('.order-list');
    if (!orderList) return;

    const orders = JSON.parse(localStorage.getItem('orders') || '[]');
    
    if (orders.length === 0) {
        orderList.innerHTML = '<div class="empty-orders">暂无订单</div>';
        return;
    }

    orderList.innerHTML = orders.map(order => {
        // 确保order.products存在且是数组
        const orderProducts = Array.isArray(order.products) ? order.products : [];
        
        return `
            <div class="order-item">
                <div class="order-header">
                    <div class="order-info">
                        <span class="order-number">订单号：${order.orderNumber || ''}</span>
                        <span class="order-date">下单时间：${order.date || ''}</span>
                    </div>
                    <span class="order-status status-${(order.status || '').toLowerCase()}">${getStatusText(order.status)}</span>
                </div>
                <div class="order-products">
                    ${orderProducts.map(product => `
                        <div class="order-product">
                            <img src="${product.image || ''}" alt="${product.name || ''}" class="order-product-image">
                            <div class="order-product-info">
                                <div class="order-product-name">${product.name || ''}</div>
                                <div class="order-product-price">¥${(product.price || 0).toFixed(2)}</div>
                                <div class="order-product-quantity">数量：${product.quantity || 0}</div>
                            </div>
                        </div>
                    `).join('')}
                </div>
                <div class="order-footer">
                    <div class="order-total">
                        总计：<span class="order-total-price">¥${(order.total || 0).toFixed(2)}</span>
                    </div>
                    <div class="order-actions">
                        ${getOrderActions(order)}
                    </div>
                </div>
            </div>
        `;
    }).join('');

    // 添加订单操作事件
    addOrderActionEvents();
}

// 获取订单状态文本
function getStatusText(status) {
    const statusMap = {
        'PENDING': '待付款',
        'COMPLETED': '已完成',
        'CANCELLED': '已取消'
    };
    return statusMap[status] || status;
}

// 获取订单操作按钮
function getOrderActions(order) {
    let actions = '';
    
    switch (order.status) {
        case 'PENDING':
            actions = `
                <button class="order-action-btn primary" data-action="pay" data-order="${order.orderNumber}">立即付款</button>
                <button class="order-action-btn danger" data-action="cancel" data-order="${order.orderNumber}">取消订单</button>
            `;
            break;
        case 'COMPLETED':
            actions = `
                <button class="order-action-btn" data-action="review" data-order="${order.orderNumber}">评价</button>
                <button class="order-action-btn primary" data-action="rebuy" data-order="${order.orderNumber}">再次购买</button>
            `;
            break;
        case 'CANCELLED':
            actions = `
                <button class="order-action-btn danger" data-action="delete" data-order="${order.orderNumber}">删除订单</button>
            `;
            break;
    }
    
    return actions;
}

// 添加订单操作事件
function addOrderActionEvents() {
    const orderActions = document.querySelectorAll('.order-action-btn');
    orderActions.forEach(btn => {
        btn.addEventListener('click', (e) => {
            const action = e.target.dataset.action;
            const orderNumber = e.target.dataset.order;
            handleOrderAction(action, orderNumber);
        });
    });
}

// 修改订单操作处理函数
function handleOrderAction(action, orderNumber) {
    let orders = JSON.parse(localStorage.getItem('orders') || '[]');
    const orderIndex = orders.findIndex(order => order.orderNumber === orderNumber);
    
    if (orderIndex === -1) return;

    switch (action) {
        case 'pay':
            // 模拟支付过程
            if (confirm('确认支付该订单？')) {
                orders[orderIndex].status = 'COMPLETED';
                showMessage('支付成功');
            }
            break;
        case 'cancel':
            // 取消订单时，将商品重新加入购物车
            if (confirm('确认取消该订单？取消后商品将返回购物车。')) {
                const cancelledOrder = orders[orderIndex];
                let cart = JSON.parse(localStorage.getItem('cart') || '[]');
                
                if (Array.isArray(cancelledOrder.products)) {
                    cancelledOrder.products.forEach(product => {
                        const existingItem = cart.find(item => item.id === product.id);
                        if (existingItem) {
                            existingItem.quantity += product.quantity;
                        } else {
                            cart.push({
                                ...product,
                                selected: true
                            });
                        }
                    });
                }
                
                localStorage.setItem('cart', JSON.stringify(cart));
                updateCart();
                
                orders[orderIndex].status = 'CANCELLED';
                showMessage('订单已取消，商品已返回购物车');
            }
            break;
        case 'delete':
            if (confirm('确认删除该订单？此操作不可恢复。')) {
                orders.splice(orderIndex, 1);
                showMessage('订单已删除');
            }
            break;
        case 'review':
            showMessage('评价功能开发中');
            break;
        case 'rebuy':
            // 将商品重新加入购物车
            const rebuyOrder = orders[orderIndex];
            let rebuyCart = JSON.parse(localStorage.getItem('cart') || '[]');
            
            if (Array.isArray(rebuyOrder.products)) {
                rebuyOrder.products.forEach(product => {
                    const existingItem = rebuyCart.find(item => item.id === product.id);
                    if (existingItem) {
                        existingItem.quantity += product.quantity;
                    } else {
                        rebuyCart.push({
                            ...product,
                            selected: true
                        });
                    }
                });
            }
            
            localStorage.setItem('cart', JSON.stringify(rebuyCart));
            updateCart();
            showMessage('商品已加入购物车');
            break;
    }

    localStorage.setItem('orders', JSON.stringify(orders));
    loadOrders();
}

// 修改结算函数
function handleCheckout() {
    const cart = JSON.parse(localStorage.getItem('cart') || '[]');
    if (cart.length === 0) {
        showMessage('购物车是空的');
        return;
    }

    if (confirm('确认提交订单？')) {
        // 创建新订单
        const newOrder = {
            orderNumber: generateOrderNumber(),
            date: new Date().toLocaleString(),
            status: 'PENDING',
            products: cart.map(item => ({
                id: item.id,
                name: item.name,
                price: item.price,
                image: item.image,
                quantity: item.quantity
            })),
            total: cart.reduce((sum, item) => sum + (item.price * item.quantity), 0)
        };

        // 保存订单
        let orders = JSON.parse(localStorage.getItem('orders') || '[]');
        orders.unshift(newOrder);
        localStorage.setItem('orders', JSON.stringify(orders));

        // 清空购物车
        localStorage.setItem('cart', '[]');
        updateCart();
        
        // 关闭购物车侧边栏
        document.getElementById('cartSidebar').classList.remove('active');
        document.getElementById('cartOverlay').classList.remove('active');

        // 显示订单模态框
        showOrderModal();
        showMessage('订单创建成功，请及时付款');
    }
}

// 生成订单号
function generateOrderNumber() {
    const date = new Date();
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const random = Math.floor(Math.random() * 10000).toString().padStart(4, '0');
    return `${year}${month}${day}${random}`;
}

// 显示个人信息模态框
function showProfileModal() {
    const profileModal = document.getElementById('profileModal');
    if (profileModal) {
        // 更新个人信息
        const username = localStorage.getItem('username');
        const registerTime = localStorage.getItem('registerTime') || new Date().toLocaleString();
        const orders = JSON.parse(localStorage.getItem('orders') || '[]');
        
        document.getElementById('profileUsername').textContent = username;
        document.getElementById('profileRegisterTime').textContent = registerTime;
        document.getElementById('profileOrderCount').textContent = orders.length;
        
        profileModal.style.display = 'block';
    }
}

// 隐藏个人信息模态框
function hideProfileModal() {
    const profileModal = document.getElementById('profileModal');
    if (profileModal) {
        profileModal.style.display = 'none';
    }
}

// 显示修改密码模态框
function showChangePasswordModal() {
    const changePasswordModal = document.getElementById('changePasswordModal');
    if (changePasswordModal) {
        changePasswordModal.style.display = 'block';
    }
}

// 隐藏修改密码模态框
function hideChangePasswordModal() {
    const changePasswordModal = document.getElementById('changePasswordModal');
    if (changePasswordModal) {
        changePasswordModal.style.display = 'none';
    }
}

// 处理退出登录
function handleLogout() {
    if (confirm('确认退出登录？')) {
        localStorage.removeItem('isLoggedIn');
        localStorage.removeItem('username');
        showMessage('已退出登录');
        hideProfileModal();
        updateLoginUI();
    }
}

// 处理修改密码
function handleChangePassword(event) {
    event.preventDefault();
    
    const oldPassword = document.getElementById('oldPassword').value;
    const newPassword = document.getElementById('newPassword').value;
    const confirmNewPassword = document.getElementById('confirmNewPassword').value;
    
    if (!oldPassword || !newPassword || !confirmNewPassword) {
        showMessage('请填写所有字段');
        return;
    }
    
    if (newPassword !== confirmNewPassword) {
        showMessage('两次输入的新密码不一致');
        return;
    }
    
    // 这里应该验证原密码，但由于是演示，我们直接模拟成功
    showMessage('密码修改成功');
    hideChangePasswordModal();
    
    // 清空表单
    event.target.reset();
}

// 显示商品详情
function showProductDetail(productId) {
    const product = products.find(p => p.id === productId);
    if (!product) return;

    const modal = document.getElementById('productDetailModal');
    const image = document.getElementById('detailProductImage');
    const name = document.getElementById('detailProductName');
    const price = document.getElementById('detailProductPrice');
    const description = document.getElementById('detailProductDescription');
    const category = document.getElementById('detailProductCategory');
    const addToCartBtn = document.getElementById('addToCartDetail');

    // 更新商品信息
    image.src = product.image;
    image.alt = product.name;
    name.textContent = product.name;
    price.textContent = `¥${product.price}`;
    description.textContent = product.description;
    category.textContent = getCategoryText(product.category);
    addToCartBtn.dataset.productId = product.id;

    // 图片加载优化
    image.onload = () => {
        image.style.opacity = '1';
    };
    image.style.opacity = '0';
    image.style.transition = 'opacity 0.3s ease';

    // 添加图片点击事件
    image.onclick = (e) => {
        e.stopPropagation();
        showImagePreview(product.image, product.name);
    };

    // 重置数量
    document.getElementById('detailQuantity').value = 1;

    // 显示模态框
    modal.style.display = 'block';
}

// 获取分类文本
function getCategoryText(category) {
    const categoryMap = {
        'phone': '手机数码',
        'computer': '电脑办公',
        'clothing': '服装鞋包',
        'food': '食品生鲜',
        'home': '家居家装'
    };
    return categoryMap[category] || category;
}

// 添加指定数量的商品到购物车
function addToCartWithQuantity(productId, quantity) {
    if (!isLoggedIn()) {
        showMessage('请先登录');
        showLoginModal();
        return;
    }

    // 获取购物车数据
    let cart = JSON.parse(localStorage.getItem('cart') || '[]');
    
    // 查找商品是否已在购物车中
    const existingItem = cart.find(item => item.id === productId);
    
    if (existingItem) {
        existingItem.quantity += quantity;
    } else {
        // 获取商品信息
        const product = products.find(p => p.id === productId);
        if (product) {
            cart.push({
                ...product,
                quantity: quantity,
                selected: true
            });
        }
    }
    
    // 保存购物车数据
    localStorage.setItem('cart', JSON.stringify(cart));
    
    // 更新待付款订单中的商品数量
    updateOrderProductQuantity(productId, existingItem ? existingItem.quantity : quantity);
    
    showMessage('已添加到购物车');
    hideProductDetailModal();
}

// 隐藏商品详情模态框
function hideProductDetailModal() {
    const modal = document.getElementById('productDetailModal');
    if (modal) {
        modal.style.display = 'none';
    }
}

// 添加显示图片预览的函数
function showImagePreview(imageUrl, imageAlt) {
    const imagePreviewModal = document.getElementById('imagePreviewModal');
    const previewImage = document.getElementById('previewImage');
    
    if (imagePreviewModal && previewImage) {
        previewImage.src = imageUrl;
        previewImage.alt = imageAlt;
        imagePreviewModal.style.display = 'block';
    }
}

// 初始化倒计时
function initCountdown() {
    const countdownElement = document.getElementById('countdown');
    if (!countdownElement) return;

    // 设置倒计时结束时间（当前时间后2小时30分钟）
    const endTime = new Date();
    endTime.setHours(endTime.getHours() + 2);
    endTime.setMinutes(endTime.getMinutes() + 30);

    function updateCountdown() {
        const now = new Date();
        const timeLeft = endTime - now;

        if (timeLeft <= 0) {
            countdownElement.textContent = '00:00:00';
            return;
        }

        const hours = Math.floor(timeLeft / (1000 * 60 * 60));
        const minutes = Math.floor((timeLeft % (1000 * 60 * 60)) / (1000 * 60));
        const seconds = Math.floor((timeLeft % (1000 * 60)) / 1000);

        countdownElement.textContent = `${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`;
    }

    // 立即更新一次
    updateCountdown();
    // 每秒更新一次
    setInterval(updateCountdown, 1000);
}

// 初始化限时秒杀功能
function initSeckill() {
    // 添加收回按钮
    const seckillContainer = document.querySelector('.seckill-container');
    const toggleButton = document.createElement('button');
    toggleButton.className = 'seckill-toggle';
    toggleButton.innerHTML = '限时秒杀◀';
    seckillContainer.appendChild(toggleButton);

    // 收回功能
    toggleButton.addEventListener('click', () => {
        seckillContainer.classList.toggle('collapsed');
        toggleButton.innerHTML = seckillContainer.classList.contains('collapsed') ? '▶' : '◀';
    });

    // 更新秒杀商品显示
    function updateSeckillItems() {
        const seckillContent = document.querySelector('.seckill-content');
        seckillContent.innerHTML = seckillProducts.map(product => `
            <div class="seckill-item" data-id="${product.id}">
                <div class="seckill-item-image">
                    <img src="${product.image}" alt="${product.name}" loading="lazy" onload="this.style.opacity='1'" onerror="this.src='https://via.placeholder.com/300x300?text=图片加载失败'">
                    <div class="seckill-stock">库存: ${product.stock - product.sold}</div>
                    <div class="seckill-countdown" data-countdown="${product.countdown}">${formatCountdown(product.countdown)}</div>
                    <div class="seckill-tag">限时秒杀</div>
                </div>
                <div class="seckill-item-info">
                    <h3>${product.name}</h3>
                    <div class="seckill-price">
                        <span class="current-price">¥${product.price}</span>
                        <span class="original-price">¥${product.originalPrice}</span>
                    </div>
                    <div class="seckill-progress">
                        <div class="progress-bar">
                            <div class="progress" style="width: ${(product.sold / product.stock) * 100}%"></div>
                        </div>
                        <span class="progress-text">已抢${Math.round((product.sold / product.stock) * 100)}%</span>
                    </div>
                    <button class="seckill-buy-btn" data-id="${product.id}">
                        ${product.sold >= product.stock ? '已售罄' : '立即抢购'}
                    </button>
                </div>
            </div>
        `).join('');

        // 添加点击事件
        addSeckillItemEvents();
    }

    // 格式化倒计时
    function formatCountdown(seconds) {
        const hours = Math.floor(seconds / 3600);
        const minutes = Math.floor((seconds % 3600) / 60);
        const secs = seconds % 60;
        return `${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}:${String(secs).padStart(2, '0')}`;
    }

    // 初始化显示
    updateSeckillItems();

    // 更新倒计时
    function updateCountdown() {
        const countdownElements = document.querySelectorAll('.seckill-countdown');
        countdownElements.forEach((element, index) => {
            const product = seckillProducts[index];
            if (product && product.countdown > 0) {
                product.countdown--;
                element.textContent = formatCountdown(product.countdown);
                element.dataset.countdown = product.countdown;
            }
        });
    }

    // 每秒更新倒计时
    setInterval(updateCountdown, 1000);
}

// 添加秒杀商品事件处理
function addSeckillItemEvents() {
    const seckillItems = document.querySelectorAll('.seckill-item');
    const seckillBuyBtns = document.querySelectorAll('.seckill-buy-btn');

    seckillItems.forEach(item => {
        item.addEventListener('click', (e) => {
            if (!e.target.classList.contains('seckill-buy-btn')) {
                const productId = parseInt(item.dataset.id);
                showSeckillProductDetail(productId);
            }
        });
    });

    seckillBuyBtns.forEach(btn => {
        btn.addEventListener('click', (e) => {
            e.stopPropagation();
            const productId = parseInt(btn.dataset.id);
            handleSeckillBuy(productId);
        });
    });
}

// 显示秒杀商品详情
function showSeckillProductDetail(productId) {
    const product = seckillProducts.find(p => p.id === productId);
    if (!product) return;

    const modal = document.getElementById('seckillModal');
    if (!modal) return;

    const modalContent = modal.querySelector('.seckill-modal-content');
    if (!modalContent) return;

    modalContent.innerHTML = `
        <div class="seckill-modal-header">
            <h3 class="seckill-modal-title">商品详情</h3>
            <button class="seckill-modal-close">&times;</button>
        </div>
        <div class="seckill-modal-body">
            <div class="seckill-modal-info">
                <img src="${product.image}" alt="${product.name}" class="seckill-modal-image">
                <div class="seckill-modal-details">
                    <h4 class="seckill-modal-name">${product.name}</h4>
                    <div class="seckill-modal-price">¥${product.price}</div>
                    <div class="seckill-modal-quantity">
                        <label>数量：</label>
                        <input type="number" value="1" min="1" max="${product.stock - product.sold}">
                    </div>
                </div>
            </div>
        </div>
        <div class="seckill-modal-footer">
            <button class="seckill-modal-btn secondary">取消</button>
            <button class="seckill-modal-btn primary">立即抢购</button>
        </div>
    `;

    // 添加关闭按钮事件
    const closeBtn = modalContent.querySelector('.seckill-modal-close');
    const cancelBtn = modalContent.querySelector('.seckill-modal-btn.secondary');
    const buyBtn = modalContent.querySelector('.seckill-modal-btn.primary');

    closeBtn.addEventListener('click', () => {
        modal.style.display = 'none';
    });

    cancelBtn.addEventListener('click', () => {
        modal.style.display = 'none';
    });

    buyBtn.addEventListener('click', () => {
        const quantity = parseInt(modalContent.querySelector('input[type="number"]').value);
        handleSeckillBuy(productId, quantity);
        modal.style.display = 'none';
    });

    modal.style.display = 'block';
}

// 处理秒杀购买
function handleSeckillBuy(productId, quantity = 1) {
    if (!isLoggedIn()) {
        showMessage('请先登录');
        showLoginModal();
        return;
    }

    const product = seckillProducts.find(p => p.id === productId);
    if (!product) return;

    if (product.sold >= product.stock) {
        showMessage('商品已售罄');
        return;
    }

    // 获取购物车数据
    let cart = JSON.parse(localStorage.getItem('cart') || '[]');
    
    // 查找商品是否已在购物车中
    const existingItem = cart.find(item => item.id === productId);
    
    if (existingItem) {
        existingItem.quantity += quantity;
    } else {
        // 添加秒杀商品到购物车
        cart.push({
            ...product,
            quantity: quantity,
            selected: true
        });
    }
    
    // 更新商品销量
    product.sold += quantity;
    
    // 保存购物车数据
    localStorage.setItem('cart', JSON.stringify(cart));
    
    // 更新购物车显示
    updateCart();
    
    showMessage('抢购成功，已加入购物车');
}

// 初始化主题
function initTheme() {
    const themeToggle = document.getElementById('themeToggle');
    const themeOptions = document.querySelectorAll('.theme-option');
    const themeIcon = themeToggle.querySelector('.theme-icon');
    
    // 从localStorage获取保存的主题
    const savedTheme = localStorage.getItem('theme') || 'default';
    document.documentElement.setAttribute('data-theme', savedTheme);
    updateThemeIcon(savedTheme);

    // 主题切换按钮点击事件
    themeToggle.addEventListener('click', (e) => {
        e.stopPropagation();
        const menu = document.querySelector('.theme-menu');
        menu.style.display = menu.style.display === 'block' ? 'none' : 'block';
    });

    // 主题选项点击事件
    themeOptions.forEach(option => {
        option.addEventListener('click', () => {
            const theme = option.dataset.theme;
            document.documentElement.setAttribute('data-theme', theme);
            localStorage.setItem('theme', theme);
            updateThemeIcon(theme);
            document.querySelector('.theme-menu').style.display = 'none';
        });
    });

    // 点击页面其他地方关闭主题菜单
    document.addEventListener('click', () => {
        document.querySelector('.theme-menu').style.display = 'none';
    });
}

// 更新主题图标
function updateThemeIcon(theme) {
    const themeIcon = document.querySelector('.theme-icon');
    const icons = {
        'default': '🌙',
        'dark': '🌑',
        'light': '☀️',
        'blue': '💙',
        'green': '💚'
    };
    themeIcon.textContent = icons[theme] || '🌙';
}

// 初始化浮动广告
function initFloatingAd() {
    // 创建广告元素
    const floatingAd = document.createElement('div');
    floatingAd.id = 'floatingAd';
    floatingAd.className = 'floating-ad';
    floatingAd.style.cssText = `
        position: fixed;
        bottom: 20px;
        right: 20px;
        background: #fff;
        padding: 15px;
        border-radius: 8px;
        box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        z-index: 1000;
        display: none;
        width: 280px;
    `;
    
    // 创建广告内容
    floatingAd.innerHTML = `
        <div style="position: relative;">
            <button type="button" id="closeAdBtn" style="
                position: absolute;
                top: -10px;
                right: -10px;
                background: #ff4444;
                color: white;
                border: none;
                border-radius: 50%;
                width: 24px;
                height: 24px;
                line-height: 24px;
                text-align: center;
                cursor: pointer;
                font-size: 16px;
                padding: 0;
                z-index: 1001;
            ">&times;</button>
            <img src="https://images.unsplash.com/photo-1607082348824-0a96f2a4b9da?w=500&auto=format&fit=crop&q=60" 
                 alt="限时特惠" 
                 style="
                    width: 100%;
                    height: 150px;
                    object-fit: cover;
                    border-radius: 6px;
                    margin-bottom: 10px;
                 "
            >
            <div style="
                margin-bottom: 10px;
                font-size: 16px;
                color: #333;
                font-weight: bold;
            ">限时特惠！全场商品8折起</div>
            <button type="button" id="viewProductsBtn" style="
                background: #ff6b6b;
                color: white;
                border: none;
                padding: 8px 15px;
                border-radius: 4px;
                cursor: pointer;
                width: 100%;
                font-weight: bold;
            ">立即查看</button>
        </div>
    `;
    
    document.body.appendChild(floatingAd);

    // 延迟显示广告（1秒后）
    setTimeout(() => {
        floatingAd.style.display = 'block';
    }, 1000);

    // 关闭按钮点击事件
    const closeAdBtn = document.getElementById('closeAdBtn');
    if (closeAdBtn) {
        closeAdBtn.addEventListener('click', () => {
            floatingAd.style.display = 'none';
        });
    }

    // 查看商品按钮点击事件
    const viewProductsBtn = document.getElementById('viewProductsBtn');
    if (viewProductsBtn) {
        viewProductsBtn.addEventListener('click', () => {
            floatingAd.style.display = 'none';
            document.querySelector('.product-container')?.scrollIntoView({behavior: 'smooth'});
        });
    }
}

// 初始化在线客服功能
function initCustomerService() {
    const csButton = document.querySelector('.cs-button');
    const csChatBox = document.querySelector('.cs-chat-box');
    const csClose = document.querySelector('.cs-close');
    const csInput = document.querySelector('.cs-chat-input input');
    const csSend = document.querySelector('.cs-chat-input button');
    const csMessages = document.querySelector('.cs-chat-messages');

    if (!csButton || !csChatBox || !csClose || !csInput || !csSend || !csMessages) {
        console.log('客服组件未找到');
        return;
    }

    // 显示欢迎消息
    function showWelcomeMessage() {
        const welcomeMessage = document.createElement('div');
        welcomeMessage.className = 'cs-message cs-system';
        welcomeMessage.textContent = '您好！欢迎使用在线客服，请问有什么可以帮您？';
        csMessages.appendChild(welcomeMessage);
    }

    // 添加消息到聊天框
    function addMessage(content, isUser = false) {
        const message = document.createElement('div');
        message.className = `cs-message ${isUser ? 'cs-user' : 'cs-system'}`;
        message.textContent = content;
        csMessages.appendChild(message);
        csMessages.scrollTop = csMessages.scrollHeight;
    }

    // 处理用户输入
    function handleUserInput() {
        const message = csInput.value.trim();
        if (message) {
            addMessage(message, true);
            csInput.value = '';
            
            // 模拟客服回复
            setTimeout(() => {
                const responses = [
                    '好的，我明白了。',
                    '这个问题我来帮您解决。',
                    '请稍等，我马上为您查询。',
                    '感谢您的咨询，还有什么可以帮您的吗？',
                    '您说得对，我们会认真考虑您的建议。'
                ];
                const randomResponse = responses[Math.floor(Math.random() * responses.length)];
                addMessage(randomResponse);
            }, 1000);
        }
    }

    // 打开聊天框
    csButton.addEventListener('click', () => {
        csChatBox.style.display = 'flex';
        if (csMessages.children.length === 0) {
            showWelcomeMessage();
        }
    });

    // 关闭聊天框
    csClose.addEventListener('click', () => {
        csChatBox.style.display = 'none';
    });

    // 发送消息
    csSend.addEventListener('click', handleUserInput);

    // 按回车发送消息
    csInput.addEventListener('keypress', (e) => {
        if (e.key === 'Enter') {
            handleUserInput();
        }
    });
}

// 初始化吸顶导航
function initStickyNav() {
    const categoryNav = document.querySelector('.category-nav');
    const navTop = categoryNav.offsetTop;

    function handleScroll() {
        if (window.scrollY >= navTop) {
            categoryNav.classList.add('sticky');
        } else {
            categoryNav.classList.remove('sticky');
        }
    }

    // 添加滚动事件监听
    window.addEventListener('scroll', handleScroll);
    // 初始检查一次
    handleScroll();
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', initPage); 